extends ColorRect

var direction = Vector2(1,1)
var SPEED = 200

var active = false

onready var PLATFORM1 = $"../PLATFORM1"
onready var PLATFORM2 = $"../PLATFORM2"
onready var NYA = $"../NYA"
onready var vp = get_viewport()
onready var amplifier = AudioServer.get_bus_effect(AudioServer.get_bus_index($Hummer3.bus),0)
onready var p_shifter = AudioServer.get_bus_effect(AudioServer.get_bus_index($Hummer3.bus),1)


var pulse_incoming = 5
var pulse_outgoing = 3

var phase = 0.0
export var pulse_hz = 5
var amplitude_db = 5.0
var pitch_amplitude = 0.01


func _ready():
	randomize()
	reset()

func start():
	active = true
	direction = Vector2(rand_plus_minus(),rand_plus_minus())

func rand_plus_minus():
	var res = (randi() % 2) * 2 - 1
	print (res)
	return res

func reset():

	rect_position = vp.size/2.0-rect_size/2.0
	$"../ScoreLabel".reset()


func _process(delta):
	pulse_hz = pulse_incoming if direction.y > 0 else pulse_outgoing
	var increment = delta * pulse_hz
	var sine = sin(phase * (PI * 2.0))
	amplifier.volume_db = (rect_position.y/vp.size.y-1)*20+sine*amplitude_db
	p_shifter.pitch_scale = 1+sine*pitch_amplitude
	phase = fmod((phase + increment), 1.0)

	if active:
		var newpos = rect_position+Vector2(SPEED*delta*sign(direction.x), SPEED*delta*sign(direction.y))
		if not (newpos.x > 0 and newpos.x < vp.size.x-rect_size.x):
			direction.x = -direction.x
			pam()
			_process(delta)
			return

		if newpos.y+rect_size.y > vp.size.y or newpos.y < 0:
			lose()
			return

		if newpos.y<=PLATFORM1.rect_size.y:
			check_and_hit(PLATFORM1,newpos,delta)
			return
		if newpos.y+rect_size.y>=vp.size.y - PLATFORM2.rect_size.y:
			check_and_hit(PLATFORM2,newpos,delta)
			return
		rect_position = newpos

func increment_score():
	$"../ScoreLabel".bump_score()
	pass

func pam():
	$PAM.play()

func lose():
	NYA.nya(self)
	reset()
	active = false
	$"../START_LABEL".activate()

func check_and_hit(platform,newpos,delta):
	if  newpos.x+rect_size.x >= platform.rect_position.x and newpos.x <= platform.rect_position.x+platform.rect_size.x:
			if  abs(platform.rect_size.y - min (newpos.y, vp.size.y-newpos.y-rect_size.y)) < SPEED*delta:
				increment_score()
				platform.ping()
				direction.y = -direction.y
				_process(delta)
				return
	rect_position = newpos
